# tohtml class is used to convert the specific datas to html format
# This class takes as parameters:
# 1. summary
# 2. threatNameComparisonData
# 3. hostComparisonData
# 4. ipLocationComparisonData
# 5. networkFileComparisonData
# 6. traitComparisonData
# Sequence of actions are implemented in execute()
# File to be created is 'SummaryData.html'

# HTML library is used to call or HTML.Table
import HTML
import json
# Constant to create inner table. 
# No outside border, to make the table looks simple and neat.
TABLE_STYLE_NOBORDER = "border: 1px solid #FFFFFF; border-collapse: collapse;"

class SummaryToHTML:
    # intialise parameters and file to be created and written
    def __init__(self, summary, threatNameComparisonData, hostComparisonData, 
                 ipLocationComparisonData, networkFileComparisonData, traitComparisonData,
                 traitComResStats):
        self.file = open('SummaryData.html', 'w')
        self.summary = summary
        self.threatNameComparisonData = threatNameComparisonData
        self.hostComparisonData = hostComparisonData
        self.ipLocationComparisonData = ipLocationComparisonData
        self.networkFileComparisonData = networkFileComparisonData
        self.traitComparisonData = traitComparisonData
        self.traitComResStats = traitComResStats
        
    # method to initiate sequence of actions
    def execute(self):
        self.writeHeader()
        self.drawHistogramStats()
        self.writeSummary()
        self.writeThreatCompRes()
        self.writeHostCompRes()
        self.writeIPLocationCompRes()
        self.writeNetworkFileCompRes()
        self.writeTraitCompRes()
        self.writeFooter()
    # write as header - doc type and title for html file       
    def writeHeader(self):
        self.file.write("<!DOCTYPE html><html lang=\"en\"><head><link rel=\"stylesheet\" href=\"style.css\" /><title>ASDS</title></head><body>")          
    # write as footer - closing body and html tags
    def writeFooter(self):
        self.file.write("</body></html>")
        self.file.close()
    # write summary as table
    def writeSummary(self):
        t = HTML.Table(header_row=['<a name=\"Summary\"></a>Summary', 'Result'], col_width=(130,))
        for summary in sorted(self.summary):
            subt = HTML.Table(col_width=(270,80), style = TABLE_STYLE_NOBORDER)
            if summary == "Trait":
                pass
            else:
                for result in sorted(self.summary[summary]):
                    summaryLink = "<a href=\"#%s\">%s</a>" % (summary, summary)
                    subt.rows.append([result,str(self.summary[summary][result])])
                    subt_htmlcode = str(subt)
                t.rows.append([summaryLink,subt_htmlcode])
        htmlcode = str(t)
        self.file.write(htmlcode)
        self.writeBreak()

    # write breaks/enter spaces
    def writeBreak(self):
        self.file.write("<br><br></br></br>")
    # write the threat comparison data in a table
    def writeThreatCompRes(self):
        if self.threatNameComparisonData:
            self.file.write("<a href=\"#Summary\">Go to top</a>")      # Link to the top of Summary Table
            t = HTML.Table(header_row=['<a name=\"Threat Name\"></a>Threat Name', 'Set A', 'Set B'], col_width=(150, 320, 320))
            for threatName in sorted(self.threatNameComparisonData ):
                listA = self.threatNameComparisonData[threatName]["Set A"]
                listB = self.threatNameComparisonData[threatName]["Set B"]
                subtA = HTML.Table(col_width=(320,), style = TABLE_STYLE_NOBORDER)
                subtB = HTML.Table(col_width=(320,), style = TABLE_STYLE_NOBORDER)
                for md5 in sorted(listA):
                    subtA.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>"])
                for md5 in sorted(listB):
                    subtB.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>"])
                t.rows.append([threatName,subtA,subtB])
            htmlcode = str(t)       
            self.file.write(htmlcode)
            self.writeBreak()

    # write the host comparison data in a table
    def writeHostCompRes(self):
        if self.hostComparisonData:
            self.file.write("<a href=\"#Summary\">Go to top</a>")   # Link to the top of Summary Table
            t = HTML.Table(header_row=['<a name=\"Host\"></a>Host', 'Set A', 'Set B'], col_width=(150, 350, 350))
            for host in sorted(self.hostComparisonData):
                subtA = HTML.Table(col_width=(200,100), style = TABLE_STYLE_NOBORDER)
                subtB = HTML.Table(col_width=(200,100), style = TABLE_STYLE_NOBORDER)
                for md5 in self.hostComparisonData[host]["Set A"]:
                    sub_subtA = HTML.Table(col_width=(100,), style = TABLE_STYLE_NOBORDER)
                    actionListA = self.hostComparisonData[host]["Set A"][md5]
                    for action in actionListA:
                        sub_subtA.rows.append([action])
                    subtA.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>", sub_subtA])
    
                for md5 in self.hostComparisonData[host]["Set B"]:
                    sub_subtB = HTML.Table(col_width=(100,), style = TABLE_STYLE_NOBORDER)
                    actionListB = self.hostComparisonData[host]["Set B"][md5]
                    for action in actionListB:
                        sub_subtB.rows.append([action])
                    subtB.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>", sub_subtB])
                t.rows.append([host,subtA,subtB])
            htmlcode = str(t)
            self.file.write(htmlcode)
            self.writeBreak()

    # write the IP location comparison data in a table
    def writeIPLocationCompRes(self):
        if self.ipLocationComparisonData:
            self.file.write("<a href=\"#Summary\">Go to top</a>")      # Link to the top of Summary Table
            t = HTML.Table(header_row=['<a name=\"IP Location\"></a>IP Location', 'Set A', 'Set B'], col_width=(150, 350, 350))
            for location in sorted(self.ipLocationComparisonData):
                subtA = HTML.Table(col_width=(200,100), style = TABLE_STYLE_NOBORDER)
                subtB = HTML.Table(col_width=(200,100), style = TABLE_STYLE_NOBORDER)
                for md5 in self.ipLocationComparisonData[location]["Set A"]:
                    sub_subtA = HTML.Table(col_width=(100,), style = TABLE_STYLE_NOBORDER)
                    ipListA = self.ipLocationComparisonData[location]["Set A"][md5]
                    for ip in ipListA:
                        sub_subtA.rows.append([ip])
                    subtA.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>", sub_subtA])      
                for md5 in self.ipLocationComparisonData[location]["Set B"]:
                    sub_subtB = HTML.Table(col_width=(100,), style = TABLE_STYLE_NOBORDER)
                    ipListB = self.ipLocationComparisonData[location]["Set B"][md5]
                    for ip in ipListB:
                        sub_subtB.rows.append([ip])
                    subtB.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>", sub_subtB])
                t.rows.append([location,subtA,subtB])
            htmlcode = str(t)
            self.file.write(htmlcode)
            self.writeBreak()

    # write the network file comparison data in a table
    def writeNetworkFileCompRes(self):
        if self.networkFileComparisonData:
            self.file.write("<a href=\"#Summary\">Go to top</a>")    # Link to the top of Summary Table
            t = HTML.Table(header_row=['<a name=\"Network Files\"></a>Network Files', 'Set A', 'Set B'], col_width=(150, 600, 600))
            for networkFile in sorted(self.networkFileComparisonData):
                subtA = HTML.Table(col_width=(200,400), style = TABLE_STYLE_NOBORDER)
                subtB = HTML.Table(col_width=(200,400), style = TABLE_STYLE_NOBORDER)
                for md5 in self.networkFileComparisonData[networkFile]["Set A"]:
                    sub_subtA = HTML.Table(col_width=(400,), style = TABLE_STYLE_NOBORDER)
                    networkList = self.networkFileComparisonData[networkFile]["Set A"][md5]
                    for network in networkList:
                        sub_subtA.rows.append([network])
                    subtA.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>", sub_subtA])      
                for md5 in self.networkFileComparisonData[networkFile]["Set B"]:
                    sub_subtB = HTML.Table(col_width=(400,), style = TABLE_STYLE_NOBORDER)
                    networkList = self.networkFileComparisonData[networkFile]["Set B"][md5]
                    for network in networkList:
                        sub_subtB.rows.append([network])
                    subtB.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>", sub_subtB])
                t.rows.append([networkFile,subtA,subtB])
            htmlcode = str(t)
            self.file.write(htmlcode)    
            self.writeBreak()

    # write the trait comparison data in a table
    def writeTraitCompRes(self):
        if self.traitComparisonData:
            self.file.write('<a name=\"Trait\"></a><a name=\"Trait Objects\"></a>')
            for traitObject in self.traitComparisonData:      
                t = HTML.Table(header_row=['<a name=\"'+traitObject+'\"></a>'+traitObject+''], col_width=(150+100+800+800,))
                subt = HTML.Table(col_width=(50,100,800,800), style = TABLE_STYLE_NOBORDER)
                subt.rows.append(['No', 'Match %', 'Set A', 'Set B'])
                for number in  self.traitComparisonData[traitObject]:
                    matchLevel = self.traitComparisonData[traitObject][number]["Match %"]
                    subtA = HTML.Table(col_width=(200,600), style = TABLE_STYLE_NOBORDER)
                    subtB = HTML.Table(col_width=(200,600), style = TABLE_STYLE_NOBORDER)
    
                    for md5 in sorted(self.traitComparisonData[traitObject][number]["Set A"]):
                        sub_subtA = HTML.Table(col_width=(200,400), style = TABLE_STYLE_NOBORDER)
                        for traitItem in sorted(self.traitComparisonData[traitObject][number]["Set A"][md5]):
                            sub_subtA.rows.append([traitItem,self.traitComparisonData[traitObject][number]["Set A"][md5][traitItem]])
                        subtA.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>",sub_subtA]) 
    
                    for md5 in sorted(self.traitComparisonData[traitObject][number]["Set B"]):
                        sub_subtB = HTML.Table(col_width=(200,400), style = TABLE_STYLE_NOBORDER)
                        for traitItem in sorted(self.traitComparisonData[traitObject][number]["Set B"][md5]):
                            sub_subtB.rows.append([traitItem,self.traitComparisonData[traitObject][number]["Set B"][md5][traitItem]])
                        subtB.rows.append(["<a href=\"http://rats.gist.symantec.com/rats/sample/traits/"+md5+"\">"+md5+"</a>",sub_subtB]) 
                    subt.rows.append([number, matchLevel,subtA, subtB])      
                t.rows.append([subt])       
                htmlcode = str(t)
                self.file.write("<a href=\"#Summary\">Go to top</a>")    # Link to the top of Summary Table
                self.file.write(htmlcode)  
                self.writeBreak()
    
    def drawHistogramSummary(self):
        categories = sorted(self.summary.keys())
        if 'Trait' in categories:
            categories.remove('Trait')
            
        simData = []
        setAData = []
        setBData = []
        for category in categories:
            simData.append(self.summary[category][category + " Similarity"])
            setAData.append(self.summary[category][category + " in set A"])
            setBData.append(self.summary[category][category + " in set B"])
                      
        series = [{
                "name": 'Similarity',
                "data": simData
    
            }, {
                "name": 'Set A',
                "data": setAData
    
            }, {
                "name": 'Set B',
                "data": setBData
            }]
    
        categoriesStr = json.dumps(categories, indent = 2)
        seriesStr = json.dumps(series, indent = 2)
        
        # histogram header
        self.file.write(" <script type=\"text/javascript\" "+
                        " src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js\"></script> "+
                        " <script type=\"text/javascript\"> ")
    
        # histogram data
        self.file.write(" $(function () { "+
                        " $('#container').highcharts({ "+
                        " chart: { "+
                            " type: 'column' "+
                        " }, "+
                        " title: { "+
                            " text: 'Attack Campaign Similarity' "+
                        " }, "+
                        " yAxis: { "+
                            " min: 0, "+
                            " title: { "+
                            " text: 'No of Similarity' "+
                            " } "+
                        " }, "+
                        " tooltip: { "+
                            " headerFormat: '<span style=\"font-size:10px\">{point.key}</span><table>', "+
                            " pointFormat: '<tr><td style=\"color:{series.color};padding:0\">{series.name}: </td>' + "+
                                         " '<td style=\"padding:0\"><b>{point.y:.1f} mm</b></td></tr>', "+
                            " footerFormat: '</table>', "+
                            " shared: true, "+
                            " useHTML: true "+
                        " }, "+
                        " plotOptions: { "+
                            " column: { "+
                            " pointPadding: 0.2, "+
                            " borderWidth: 0 "+
                            " } "+
                            " }, "+
                        " xAxis: { "+
                            " categories: "+
                                categoriesStr+                             
                        " }, "+
                        " series: "+
                            seriesStr+
                        " }); "+
                        " }); ")
        
        # histogram footer
        self.file.write(" </script></head><body> "+
                        " <script src=\"Highcharts-4.0.1/js/highcharts.js\"></script> "+
                        " <script src=\"Highcharts-4.0.1/js/modules/exporting.js\"></script> "+
                        " <div id=\"container\" style=\"min-width: 310px; height: 400px; margin: 0 auto\"></div> ")
        self.writeBreak()

    def drawHistogramStats(self):
        categories = sorted(self.summary.keys())
        if 'Trait' in categories:
            categories.remove('Trait')
            
        totalMatches = []
        moreThan50 = []
        lessThan50 = []
        for category in categories:
            if self.traitComResStats.has_key(category):
                totalMatches.append(self.traitComResStats[category]["Total Matches"])
                moreThan50.append(self.traitComResStats[category]["> 50% matched"])
                lessThan50.append(self.traitComResStats[category]["< 50% matched"])
            else:
                totalMatches.append(self.summary[category][category + " Similarity"])
                moreThan50.append(self.summary[category][category + " Similarity"])
                lessThan50.append(0)
                
                      
        series = [{
                "name": 'Total Matches',
                "data": totalMatches
    
            }, {
                "name": '> 50% matched',
                "data": moreThan50
                
            }, {
                "name": '< 50% matched',
                "data": lessThan50
    
            }]
    
        categoriesStr = json.dumps(categories, indent = 2)
        seriesStr = json.dumps(series, indent = 2)
        
        # histogram header
        self.file.write(" <script type=\"text/javascript\" "+
                        " src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js\"></script> "+
                        " <script type=\"text/javascript\"> ")
    
        # histogram data
        self.file.write(" $(function () { "+
                        " $('#container').highcharts({ "+
                        " chart: { "+
                            " type: 'column' "+
                        " }, "+
                        " title: { "+
                            " text: 'Attack Campaign Statistics' "+
                        " }, "+
                        " yAxis: { "+
                            " min: 0, "+
                            " title: { "+
                            " text: 'No of Similarity' "+
                            " } "+
                        " }, "+
                        " tooltip: { "+
                            " headerFormat: '<span style=\"font-size:10px\">{point.key}</span><table>', "+
                            " pointFormat: '<tr><td style=\"color:{series.color};padding:0\">{series.name}: </td>' + "+
                                         " '<td style=\"padding:0\"><b>{point.y}</b></td></tr>', "+
                            " footerFormat: '</table>', "+
                            " shared: true, "+
                            " useHTML: true "+
                        " }, "+
                        " plotOptions: { "+
                            " column: { "+
                            " pointPadding: 0.2, "+
                            " borderWidth: 0 "+
                            " } "+
                            " }, "+
                        " xAxis: { "+
                            " categories: "+
                                categoriesStr+                             
                        " }, "+
                        " series: "+
                            seriesStr+
                        " }); "+
                        " }); ")
        
        # histogram footer
        self.file.write(" </script></head><body> "+
                        " <script src=\"Highcharts-4.0.1/js/highcharts.js\"></script> "+
                        " <script src=\"Highcharts-4.0.1/js/modules/exporting.js\"></script> "+
                        " <div id=\"container\" style=\"min-width: 310px; height: 400px; margin: 0 auto\"></div> ")
               
        
        
        
        
        
        